﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Net;
using System.Threading;
using BLL;
using Microsoft.WindowsAzure;
using Microsoft.WindowsAzure.Diagnostics;
using Microsoft.WindowsAzure.ServiceRuntime;
using Microsoft.WindowsAzure.StorageClient;
using Microsoft.WindowsAzure.StorageClient.Protocol;

namespace Validator
{
    public class WorkerRole : RoleEntryPoint
    {
        public override void Run()
        {
            while (true)
            {
                var queue = QuestionManager.GetQue();
                var newMessage = queue.GetMessage();
                if (newMessage != null)
                {
                    var msgString = newMessage.AsString;
                    var fromQue = AnswerToQue.DeSerialize(msgString);
                    var manager = new QuestionManager();
                    var iscoret = manager.IsValid(fromQue.QuestionID, fromQue.OptionID);
                    var answerToStore = new tableanswers
                                            {
                                                optionid = fromQue.OptionID,
                                                questionid = fromQue.QuestionID,
                                                iscorect = iscoret,
                                                userid = fromQue.UserID
                                            };

                    AnswersStorage.AddAnswer(answerToStore);
                    queue.DeleteMessage(newMessage);
                }
                else
                    Thread.Sleep(TimeSpan.FromSeconds(100));
            }
        }

        public override bool OnStart()
        {
            // Set the maximum number of concurrent connections 
            ServicePointManager.DefaultConnectionLimit = 12;

            // For information on handling configuration changes
            // see the MSDN topic at http://go.microsoft.com/fwlink/?LinkId=166357.

            return base.OnStart();
        }
    }
}
